import re
import logging

from django.shortcuts import render

from mac.models import MacGenerateRecode
from mac import models

logger = logging.getLogger(__name__)


def mac_generate_record(request, mac, mac_nums, nid, product_id):
    dict_mac = {}
    product_obj = models.Product.objects.filter(id=product_id).first()
    mac_inc = int(product_obj.mac_inc)
    mac_int = int(mac, 16)
    new_mac_int = mac_int + int(mac_nums)*mac_inc
    if not mac.startswith('0'):
        mac_end = hex(new_mac_int).replace('0x', '').upper()
        mac_end = mac_end[:-1] + 'F'
        next_mac_end = hex(int(mac_end, 16) + 1).replace('0x', '').upper()
    else:
        m = re.match(r'^[0]+', mac)
        if m:
            mac_end = hex(new_mac_int).replace('0x', m.group(0)).upper()
            mac_end = mac_end[:-1] + 'F'
            next_mac_end = hex(int(mac_end, 16) + 1).replace('0x', m.group(0)).upper()
    id_identification = str(int(nid)+1) + '_' + str(int(nid)+int(mac_nums))
    dict_mac['product_name'] = product_obj.name
    dict_mac['hardware_name'] = mac + '-' + mac_nums + '-' + product_obj.board
    dict_mac['board'] = product_obj.board
    dict_mac['mac_start'] = mac
    dict_mac['mac_end'] = mac_end
    dict_mac['mac_nums'] = int(mac_nums)
    dict_mac['id_identification'] = id_identification
    dict_mac['user_id_id'] = request.mac.user.id
    server_error = None
    try:
        MacGenerateRecode.objects.create(**dict_mac)
    except UnicodeError as e:
        logger.error(e)
        server_error = render(request, '500.html')
        return server_error
    return next_mac_end, product_obj, server_error
